package cloudPayAdmin.admin.controller.hicatcard.distributor;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cloudPayAdmin.admin.dbapp.entity.hicatcard.card.TCard;
import cloudPayAdmin.admin.dbapp.entity.hicatcard.distributor.TDistributor;
import cloudPayAdmin.admin.dbapp.entity.hicatcard.user.TUserCard;
import cloudPayAdmin.admin.dbapp.vo.hicatcard.VCardCoupon;
import cloudPayAdmin.admin.dbapp.vo.hicatcard.VDistributorPerson;
import cloudPayAdmin.admin.dbapp.vo.hicatcard.VPayOrder;
import cloudPayAdmin.admin.service.hicatcard.distributor.DistributorPersonService;
import cloudPayAdmin.admin.service.hicatcard.distributor.DistributorService;
import cloudPayAdmin.constant.Constant;
import cloudPayAdmin.util.AdminLteDataTableResp;
import cloudPayAdmin.util.AdminLteUtil;
import cloudPayAdmin.util.AdminUserInfoUtil;
import cloudPayAdmin.util.HttpUtil;
import cloudPayAdmin.util.IdGenerator;
import cloudPayAdmin.util.ImageUrlUtil;
import cloudPayAdmin.util.TimeUtil;
import cloudPayAdmin.util.WebUtil;
import cloudPayAdmin.util.WxApiUtil;
import cloudPayAdmin.util.pagebean.HqlPageBeanHelper;
import cloudPayAdmin.util.pagebean.HqlParam;
import cloudPayAdmin.util.pagebean.PageBean;

@Controller
@RequestMapping("/hicatcard/distributor")
public class DistributorController {
	
	@Autowired
	HqlPageBeanHelper hqlPageBeanHelper;

	@PersistenceContext(unitName = "entityManagerFactory")
	EntityManager entityManager;
	
	@Autowired
	Environment env;
	
	@Autowired
	DistributorService distributorService;
	
	@Autowired
	DistributorPersonService distributorPersonService;
	
	@RequestMapping(value = "/toDistributorListPage")
	public String toDistributorListPage(HttpServletRequest request, Map<String, Object> model) {
	    List<TDistributor> distributorList =  distributorService.findAll();
		request.setAttribute("distributorList", distributorList);
		request.setAttribute("statusMap", TDistributor.initStatusMap());
		request.setAttribute("typeMap", TDistributor.initTypeMap());
		return "hicatcard/distributor/distributor-list";
	}
	
	/**
	 * 跳转到 分销商统计页面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/toDistributorStatisticsPage")
	public String toDistributorStatisticsPage(HttpServletRequest request, Map<String, Object> model) {
		List<TDistributor> distributorList = distributorService.findAll();
		request.setAttribute("distributorList", distributorList);
		return "hicatcard/distributor/distributor-statistics";
	}
	
	@RequestMapping("/getDistributorStatisticsData")
	@ResponseBody
	public String getDistributorStatisticsData(HttpServletRequest request) {
		
		Map<String, Object> paramMap = WebUtil.getSearchParam(request);
		paramMap = WebUtil.formatDateRange(paramMap, TimeUtil.DATE_PATTERN_NOSEPARTOR);
		// 需要映射的实体类
		HqlParam hqlParam = WebUtil.buildHqlParam(paramMap, VDistributorPerson.class, request);
		
		//如果有 进入方式的 筛选条件
		String entryType = request.getParameter("entryType");
		if(StringUtils.isNotEmpty(entryType)) {
			String hql = hqlParam.getHql();  
			
			String[] hqlSplit = StringUtils.splitByWholeSeparator(hql, "1=1");
			
			String hqlBefore = hqlSplit[0] + "1=1";
			String hqlAfter =  hqlSplit[1];
			String newHql = null;
			if(StringUtils.equals(entryType, "1")) {        //如果筛选条件是扫码
				newHql = hqlBefore + " and u.loginFlag <> -1 " + hqlAfter;
			} else if (StringUtils.equals(entryType, "2")) {   //如果筛选条件是点击小程序
				newHql = hqlBefore + " and u.loginFlag = -1 " + hqlAfter;
			}
			
			hqlParam.setHql(newHql);
		}
		
		PageBean<VDistributorPerson> cloudpayCardPage = hqlPageBeanHelper.findHqlPageBean(entityManager, hqlParam);	
		
		for(VDistributorPerson vdp : cloudpayCardPage.getContent()) {
			Long loginFlag = vdp.getLoginFlag();
			if(loginFlag != null) {
				if(loginFlag == -1) {
					vdp.setEntryType("点击小程序");
				} else {
					TDistributor distributor = distributorService.findById(loginFlag);
					vdp.setEntryType("扫分销商 " + distributor.getName() + " 码");
				}
			}	
		}
		
		AdminLteDataTableResp<VDistributorPerson> resp = AdminLteUtil.pageBeanToAdminLteDataTableResp(cloudpayCardPage,request);
		return resp.toAdminLteJsonString(VDistributorPerson.class);
		
		/*Map<String, Object> paramMap = WebUtil.getSearchParam(request);
		paramMap = WebUtil.formatDateRange(paramMap, TimeUtil.DATE_PATTERN_NOSEPARTOR);
		// 需要映射的实体类
		HqlParam hqlParam = WebUtil.buildHqlParam(paramMap, VPayOrder.class, request);
		PageBean<VPayOrder> cloudpayCardPage = hqlPageBeanHelper.findHqlPageBean(entityManager, hqlParam);		
		AdminLteDataTableResp<VPayOrder> resp = AdminLteUtil.pageBeanToAdminLteDataTableResp(cloudpayCardPage,request);
		return resp.toAdminLteJsonString(VPayOrder.class);*/
	}
	
	@RequestMapping("/getDistributorListData")
	@ResponseBody
	public String getDistributorListData(HttpServletRequest request) {
		Map<String, Object> paramMap = WebUtil.getSearchParam(request);
		paramMap = WebUtil.formatDateRange(paramMap, TimeUtil.DATE_PATTERN_NOSEPARTOR);
		// 需要映射的实体类
		HqlParam hqlParam = WebUtil.buildHqlParam(paramMap, TDistributor.class, request);
		PageBean<TDistributor> cloudpayCardPage = hqlPageBeanHelper.findHqlPageBean(entityManager, hqlParam);
		
		//为每个分销商计算 类似扫码次数
		//筛选 扫码人数的 时间
		String scanCountTime = request.getParameter("scanCountTime");
		if(StringUtils.isNotEmpty(scanCountTime)) {
			String minScanCountTime = TimeUtil.transferDateFormat(StringUtils.splitByWholeSeparator(scanCountTime, WebUtil.DATERANGE_SEPARATOR)[0], TimeUtil.DEFAULT_DATE_PATTERN, TimeUtil.DATE_PATTERN_NOSEPARTOR);
			String maxScanCountTime = TimeUtil.transferDateFormat(StringUtils.splitByWholeSeparator(scanCountTime, WebUtil.DATERANGE_SEPARATOR)[1], TimeUtil.DEFAULT_DATE_PATTERN, TimeUtil.DATE_PATTERN_NOSEPARTOR);
			for(TDistributor distributor : cloudpayCardPage.getContent()) {
				Long scanCount = distributorPersonService.countByDistributorAndCreateTime(distributor.getDistributorId(), minScanCountTime, maxScanCountTime);
				distributor.setScanCount(scanCount);			
			}
		} else {
			for(TDistributor distributor : cloudpayCardPage.getContent()) {
			
				distributor.setScanCount(distributor.getTotalTimes().longValue());			
			}
		}
				
		for(TDistributor distributor : cloudpayCardPage.getContent()) {
			distributor.setQrcodePath(ImageUrlUtil.getFullHttpImageUrl(distributor.getQrcodePath()));
		}
		
		AdminLteDataTableResp<TDistributor> resp = AdminLteUtil.pageBeanToAdminLteDataTableResp(cloudpayCardPage,request);
		return resp.toAdminLteJsonString(TDistributor.class);
	}
	
	/**
	 * 新增 分销商 页面
	 * @return
	 */
	@RequestMapping("/toDistibutorEditPage")
	public String toDistibutorEditPage(HttpServletRequest request,Long distributorId) {
		TDistributor distributor = new TDistributor();
		if(distributorId != null) {
			distributor = distributorService.findById(distributorId);
		}
		
		request.setAttribute("distributor", distributor);
		request.setAttribute("statusMap", TDistributor.initStatusMap());
		request.setAttribute("typeMap", TDistributor.initTypeMap());
		return "hicatcard/distributor/distributor-edit";
		
	}
	
	/**
	 * 新增 分销商
	 * @param request
	 * @param distributorName
	 * @param distributorId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/editDistributor")
	public String editDistributor(HttpServletRequest request,String type,Integer protectDay,String distributorName,Long distributorId,String status) throws Exception {
		
		//新增
		if(distributorId == null) {
			
			TDistributor distributor = new TDistributor();
			String distributorNumber = IdGenerator.generateOrderId(IdGenerator.ORDERID_PREFIX_DISTRIBUTOR, "0000", "00");
			distributor.setDistributorNumber(distributorNumber);
			distributor.setName(distributorName);
			distributor.setStatus(status);
			distributor.setTotalTimes(0);
			distributor.setType(type);
			distributor.setProtectDay(protectDay);
			distributor.setCreator(AdminUserInfoUtil.getLoginAdminUserName());
			distributor.setCreateTime(TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR));
			distributor.setUpdateTime(TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR));
			
			String databasePath = env.getProperty("image.upload.database.suffix.path") + Constant.DISTRIBUTOR_PIC_FILE_PATH + HttpUtil.HTTP_PATH_SEPERATOR + distributorNumber + ".png";
			String destinationPath = env.getProperty("image.upload.base.path") + StringUtils.replaceEach(databasePath, new String[]{env.getProperty("image.upload.database.suffix.path"),HttpUtil.HTTP_PATH_SEPERATOR}, new String[]{"",File.separator});
			FileUtils.copyInputStreamToFile(WxApiUtil.getUnLimitQrCode(distributorNumber, "pages/index/index"), new File(destinationPath));
			
			distributor.setQrcodePath(databasePath);
			distributorService.saveDistributor(distributor);
		} else {          //修改
			TDistributor distributor = distributorService.findById(distributorId);
			distributor.setName(distributorName);
			distributor.setUpdateTime(TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR));
			distributor.setStatus(status);
			distributor.setType(type);
			distributor.setProtectDay(protectDay);
			distributorService.saveDistributor(distributor);
		}
		
		return "redirect:/hicatcard/distributor/toDistributorListPage";
	}
}
